<template>
  <div id="desDiv">
    <!-- 头部 -->
    <div id="headdiv">
      <span>销售出库</span>
    </div>
    <div id="sale">
      <el-button class="add-button" @click="showAddModal"
        >新增销售出库</el-button
      >
      <el-button
        type="primary"
        icon="el-icon-loading"
        class="audit-button"
        @click="handleOutAudit"
        >审核</el-button
      >
      <el-button
        class="delete-button"
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteSelected"
        >删除</el-button
      >
    </div>
    <!-- 搜索框 -->
    <div id="search-bar">
      <el-input
        placeholder="请输入表单中的内容进行搜索"
        prefix-icon="el-icon-search"
        v-model="searchKeyword"
        @change="fetchData"
        clearable
      ></el-input>
    </div>
    <div id="searchDate-bar">
      <el-button icon="el-icon-search" circle @change="fetchData"></el-button>
      <!-- 日期选择器 -->
      <el-date-picker
        v-model="searchDate"
        type="date"
        placeholder="选择日期"
        @change="fetchData"
      ></el-date-picker>
    </div>
    <!-- 躯干 -->
    <div id="bodydiv">
      <el-table
        :data="saleOutData"
        border
        stripe
        class="centered-table"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column prop="so_id" label="序号" width="60px"></el-table-column> -->
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="out_code"
          label="出库单号"
          width="150px"
        ></el-table-column>
        <el-table-column
          prop="client_head"
          label="客户姓名"
          width="120px"
        ></el-table-column>

        <el-table-column
          prop="so_packaging"
          label="打包方式"
          width="auto"
        ></el-table-column>

        <el-table-column
          prop="so_shipment_status"
          label="发货状态"
          width="auto"
        >
          <template slot-scope="scope">
            {{ scope.row.so_shipment_status == 1 ? "已发货" : "未发货" }}
          </template>
        </el-table-column>

        <el-table-column prop="outAuditStatus" label="审核状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color: scope.row.outAuditStatus == true ? '#2ab600' : 'red',
              }"
            >
              {{ scope.row.outAuditStatus == true ? "已审核" : "未审核" }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="so_status" label="订单状态" width="auto">
          <template slot-scope="scope">
            <span
              :style="{
                color:
                  scope.row.so_status == 0
                    ? 'red'
                    : scope.row.so_status == 1
                    ? 'orange'
                    : '#2ab600',
              }"
            >
              {{
                scope.row.so_status == 0
                  ? "未完成"
                  : scope.row.so_status == 1
                  ? "待出库"
                  : "已出库"
              }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          prop="employee_name"
          label="操作人员"
          width="auto"
        ></el-table-column>
        <el-table-column prop="out_sales_date" label="出库日期" width="auto">
          <template slot-scope="scope">
            <span>{{ formatDate(scope.row.out_sales_date) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              @click="handleSee(scope.row)"
              >查看</el-button
            >

            <el-button
              size="mini"
              :type="
                scope.row.out_Return_status == 1 ||
                scope.row.out_Return_status == 2
                  ? 'danger'
                  : 'primary'
              "
              :icon="scope.row.out_Return_status == 0 ? 'el-icon-back' : ''"
              :disabled="
                scope.row.out_Return_status == 1 ||
                scope.row.out_Return_status == 2
              "
              @click="handleReturn(scope.row)"
            >
              {{
                scope.row.out_Return_status == 0
                  ? "退货"
                  : scope.row.out_Return_status == 1
                  ? "待退货审核"
                  : "已退货"
              }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 下划线分隔 -->
    <el-divider></el-divider>
    <!-- 尾部 -->
    <div id="taildiv">
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        @size-change="change"
        @current-change="Ymchange"
        :current-page="currentPage"
        :page-sizes="[8, 15, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="rows"
      >
      </el-pagination>
    </div>
    <!-- 添加模态框 -->
    <el-dialog :visible.sync="isAddModalVisible" class="addmodel" width="70%">
      <div class="custom-div1">
        <el-button @click="MainAdd">提交出库</el-button>
      </div>
      <div class="custom-div">
        <span>新增销售出库</span>
      </div>
      <el-button
        class="orange-button"
        style="position: absolute; top: 43px; left: 10; padding: 10px"
        @click="returnToList"
        >返回列表</el-button
      >
      <el-form :model="formCus" class="custom-form" label-position="top">
        <div class="form-items-container">
          <div
            style="
              display: grid;
              grid-template-columns: repeat(4, 1fr);
              gap: 10px;
            "
          >
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户联系人:</label>
              <el-select
                v-model="formCus.client_head"
                auto-complete="off"
                placeholder="请选择"
                style="flex: 1; size: large"
                @change="onCustomerContactChange($event)"
              >
                <el-option
                  v-for="contact in contacts"
                  :key="contact.W_code"
                  style="width: 100%"
                  :label="contact.client_head"
                  :value="contact.client_head"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">公司名称:</label>
              <el-input
                v-model="formCus.client_name"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                placeholder="请输入公司名称"
                readonly
              >
              </el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">联系人手机:</label>
              <el-input
                v-model="formCus.client_phone"
                auto-complete="off"
                style="flex: 1"
                placeholder="请输入联系人手机"
                class="kuang"
                readonly
              ></el-input>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户属性:</label>
              <el-select
                v-model="formCus.so_c_property"
                auto-complete="off"
                placeholder="请选择客户属性"
                style="flex: 1"
              >
                <el-option
                  v-for="item in list"
                  :key="item.dd_code"
                  :label="item.dd_label"
                  style="width: 100%"
                  :value="item.dd_label"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">出库日期:</label>
              <el-date-picker
                v-model="formCus.out_sales_date"
                auto-complete="off"
                type="date"
                placeholder="选择日期"
                style="flex: 1"
                class="kuang"
              ></el-date-picker>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">操作人员:</label>
              <el-select
                v-model="formCus.employee_name"
                auto-complete="off"
                placeholder="请选择操作人员"
                style="flex: 1; size: large"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">打包方式:</label>
              <el-select
                v-model="formCus.so_packaging"
                placeholder="请选择打包方式"
                style="flex: 1"
              >
                <el-option value="散装" label="散装"></el-option>
                <el-option value="包装" label="包装"></el-option>
                <el-option value="散装/包装" label="散装/包装"></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="button-container">
          <el-button @click="proaddmodel" class="custom-button">添加</el-button>
        </div>

        <!-- 出库产品列表 -->
        <div class="product-list-container">
          <el-table :data="tableData1" border style="width: 100%">
            <el-table-column
              label="序号"
              prop="OutID"
              type="index"
              width="80"
              v-if="isgb"
            ></el-table-column>

            <el-table-column label="销售出库编号" width="180">
              <template slot-scope="scope">
                <el-input
                  prop="out_code"
                  v-model="scope.row.out_c_code"
                  placeholder="请输入出库订单号"
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="产品名称" width="180">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.orders_product_name"
                  auto-complete="off"
                  placeholder="请选择产品"
                  @change="
                    fetchWarehousesByProduct(scope.row.orders_product_name)
                  "
                >
                  <el-option
                    v-for="item in uniqueList"
                    :key="item.di_id"
                    :label="item.igi_name"
                    :value="item.igi_name"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="出库仓库" width="180">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.w_Name"
                  auto-complete="off"
                  placeholder="请选择仓库"
                  @change="
                    fetchInventoryByWarehouse(
                      scope.row,
                      scope.row.orders_product_name,
                      scope.row.w_Name
                    )
                  "
                >
                  <el-option
                    v-for="item in CK"
                    :key="item.igi_warehouse"
                    :label="item.igi_warehouse"
                    :value="item.igi_warehouse"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="订单数量" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.order_quantity"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="库存数量" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.inventory_quantity"
                  :min="0"
                  :disabled="true"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="出库数量" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.outbound_quantity"
                  :min="0"
                  :disabled="
                    scope.row.outbound_quantity > scope.row.inventory_quantity
                  "
                  @change="validateOutboundQuantity(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template>
                <el-button
                  class="caoz"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteCustomer(index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-dialog>

    <!-- 修改查看模态框 -->
    <el-dialog
      :visible.sync="isUpdateModalVisible"
      class="addmodel"
      width="70%"
    >
      <div class="custom-div1">
        <el-button @click="MainUpdate">修改</el-button>
      </div>
      <div class="custom-div">
        <span>销售出库详情</span>
      </div>
      <el-button
        class="orange-button"
        style="position: absolute; top: 43px; left: 10; padding: 10px"
        @click="returnToList"
        >返回列表</el-button
      >
      <el-form :model="formCusUpdate" class="custom-form" label-position="top">
        <div class="form-items-container">
          <div
            style="
              display: grid;
              grid-template-columns: repeat(4, 1fr);
              gap: 10px;
            "
          >
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户联系人:</label>
              <el-select
                v-model="formCusUpdate.client_head"
                auto-complete="off"
                placeholder="请选择"
                style="flex: 1; size: large"
                @change="onCustomerContactChange2($event)"
              >
                <el-option
                  v-for="contact in contacts"
                  :key="contact.W_code"
                  style="width: 100%"
                  :label="contact.client_head"
                  :value="contact.client_head"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">公司名称:</label>
              <el-input
                v-model="formCusUpdate.client_name"
                auto-complete="off"
                style="flex: 1"
                class="kuang"
                placeholder="请输入公司名称"
                readonly
              >
              </el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">联系人手机:</label>
              <el-input
                v-model="formCusUpdate.client_phone"
                auto-complete="off"
                style="flex: 1"
                placeholder="请输入联系人手机"
                class="kuang"
                readonly
              ></el-input>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">客户属性:</label>
              <el-select
                v-model="formCusUpdate.so_c_property"
                auto-complete="off"
                placeholder="请选择客户属性"
                style="flex: 1"
              >
                <el-option
                  v-for="item in list"
                  :key="item.dd_code"
                  :label="item.dd_label"
                  style="width: 100%"
                  :value="item.dd_label"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">打包方式:</label>
              <el-select
                v-model="formCusUpdate.so_packaging"
                placeholder="请选择打包方式"
                style="flex: 1"
              >
                <el-option value="散装" label="散装"></el-option>
                <el-option value="包装" label="包装"></el-option>
                <el-option value="散装/包装" label="散装/包装"></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">出库日期:</label>
              <el-date-picker
                v-model="formCusUpdate.out_sales_date"
                auto-complete="off"
                type="date"
                placeholder="选择日期"
                style="flex: 1"
                class="kuang"
              ></el-date-picker>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px">操作人员:</label>
              <el-select
                v-model="formCusUpdate.employee_name"
                auto-complete="off"
                placeholder="请选择操作人员"
                style="flex: 1; size: large"
              >
                <el-option
                  v-for="employee in employees"
                  :key="employee.employee_id"
                  style="width: 100%"
                  :label="employee.employee_name"
                  :value="employee.employee_name"
                  class="kuang"
                ></el-option>
              </el-select>
            </div>

            <div style="display: flex; align-items: center">
              <label style="width: 80px; margin-right: 10px"
                >销售出库编号:</label
              >
              <el-input
                v-model="formCusUpdate.out_code"
                auto-complete="off"
                style="flex: 1"
                placeholder=""
                class="kuang"
                :disabled="true"
              ></el-input>
            </div>
          </div>
        </div>

        <div class="button-container">
          <el-button @click="proUpdatemodel" class="custom-button"
            >添加</el-button
          >
        </div>

        <!-- 产品列表 -->
        <div class="product-list-container">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column
              label="序号"
              prop="outID"
              type="index"
              width="80"
              v-if="isgb"
            ></el-table-column>

            <el-table-column label="销售出库编号" width="170">
              <template slot-scope="scope">
                <el-input
                  prop="out_code"
                  v-model="scope.row.out_c_code"
                  placeholder="请输入出库订单号"
                >
                </el-input>
              </template>
            </el-table-column>

            <el-table-column label="产品名称" width="180">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.orders_product_name"
                  auto-complete="off"
                  placeholder="请选择产品"
                  @change="
                    fetchWarehousesByProduct(scope.row.orders_product_name)
                  "
                >
                  <el-option
                    v-for="item in uniqueList"
                    :key="item.di_id"
                    :label="item.igi_name"
                    :value="item.igi_name"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="出库仓库" width="180">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.w_Name"
                  auto-complete="off"
                  placeholder="请选择仓库"
                  @change="
                    fetchInventoryByWarehouse2(
                      scope.row,
                      scope.row.orders_product_name,
                      scope.row.w_Name
                    )
                  "
                >
                  <el-option
                    v-for="item in CK"
                    :key="item.igi_warehouse"
                    :label="item.igi_warehouse"
                    :value="item.igi_warehouse"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="订单数量" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.order_quantity"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="库存数量" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.inventory_quantity"
                  :min="0"
                  :disabled="true"
                ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="出库数量" width="180">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.outbound_quantity"
                  :min="0"
                  :disabled="
                    scope.row.outbound_quantity > scope.row.inventory_quantity
                  "
                  @change="validateOutboundQuantity2(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>

            <template>
              <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="DeleteCustomerXS(scope.row.outID)"
                    >删除</el-button
                  >

                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-check"
                    @click="confirmUpdate(scope.row)"
                    >确认</el-button
                  >
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage2"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          >
          </el-pagination>
        </div>
      </el-form>
    </el-dialog>

    <!-- 退货模态框 -->
    <el-dialog title="" :visible.sync="IshandleReturn" width="50%">
      <h3>销售出库基础信息</h3>
      <div class="custom-div2">
        <el-button @click="TuiH">退货</el-button>
      </div>
      <el-form label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货单号">
              <el-input
                v-model="addReturn.return_code"
                placeholder="自动获取系统编号"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库单号">
              <el-input
                v-model="addReturn.so_code"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期">
              <el-date-picker
                style="width: 200px"
                v-model="addReturn.return_date"
                type="date"
                format="yyyy-MM-dd"
                placeholder="请选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称">
              <el-input
                v-model="addReturn.client_head"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input
                v-model="addReturn.client_phone"
                placeholder="请输入"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="审核人">
              <el-input
                v-model="addReturn.auditor"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核时间">
              <el-input
                v-model="addReturn.auditTime"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审核状态">
              <el-input v-model="displayText2" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人员">
              <el-input
                v-model="addReturn.employee_name"
                style="width: 200px"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退货原因">
              <el-input
                v-model="addReturn.returmReason"
                placeholder="请输入"
                type="textarea"
              />
            </el-form-item>
          </el-col>
          <el-form-item
            label="外键Id"
            style="position: relative; margin-left: -180px; top: 10px"
            v-if="Ycchange"
          >
            <el-input
              v-model="addReturn.sal_sales_ReturnReturn_Id"
              v-if="Ycchange"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <h3>退货产品明细</h3>

      <div style="overflow-x: auto">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column
            prop="return_C_Id"
            type="index"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="orders_product_name"
            label="产品名称"
          ></el-table-column>

          <el-table-column
            prop="outbound_quantity"
            label="出库数量"
            width="80"
          ></el-table-column>

          <el-table-column label="退货入库仓库" width="180">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.w_Name"
                auto-complete="off"
                placeholder="请选择退货仓库"
              >
                <el-option
                  v-for="item in CK"
                  :key="item.w_Name"
                  :label="item.w_Name"
                  :value="item.w_Name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="退货数量">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_quantity"
                placeholder="请输入"
                @input="validateReturnQuantity(scope.row)"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="备注">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.return_remark"
                placeholder="请输入"
              ></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="showDispose(scope.row)" type="text"
                >移除</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            @size-change="changeModel"
            @current-change="YmchangeModel"
            :current-page="currentPage2"
            :page-sizes="[3, 6, 9, 12]"
            :page-size="pageSize2"
            layout="total, sizes, prev, pager, next, jumper"
            :total="modelfroms"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import $http from "@/routers/base";
import { MessageBox } from "element-ui";
export default {
  data() {
    return {
      products: [], //产品列表下拉数据
      productss: [],
      units: [], //单位列表下拉数据
      currentSequence: 1,
      list: [],
      CK: [], //仓库下拉
      productWarehouses: [],
      username: localStorage.getItem("username"),
      formCus: {
        out_id: "",
        out_code: "",
        client_head: "", // 客户联系人
        client_name: "", // 公司名称
        client_phone: "", // 联系人手机
        so_packaging: "", //打包方式
        so_c_property: "", //客户属性
        so_shipment_status: "", //发货状态
        employee_name: "", //操作人员
        out_sales_date: "", //销售日期

        auditor: "", //审核人
        auditTime: "", //审核时间
        out_Return_status: "", //退货状态
      },
      formCusUpdate: {
        out_id: "",
        out_code: "",
        client_head: "", // 客户联系人
        client_name: "", // 公司名称
        client_phone: "", // 联系人手机
        so_shipment_status: "", //发货状态
        so_status: "",
        so_packaging: "", //打包方式
        so_c_property: "", //客户属性
        employee_name: "", //操作人员
        out_sales_date: "", //出库日期
        outAuditStatus: "",

        auditor: "", //审核人
        auditTime: "", //审核时间
        out_Return_status: "", //退货状态
      },
      addReturn: {
        return_Id: "",
        return_code: "",
        so_code: "",
        client_head: "",
        client_phone: "",
        return_date: "",
        auditor: "",
        auditTime: "",
        outAuditStatus: "",
        employee_name: "",
        returmReason: "",

        so_out_status: "", //销售订单/出库状态
      },
      warehouseDefaults: {
        一号仓库: 100,
        二号仓库: 50,
        三号仓库: 150,
        五号仓库: 200,
      },
      contacts: [], // 包含客户联系人、公司名称和联系人电话的数据
      employees: [], //操作人员
      isAddModalVisible: false,
      isUpdateModalVisible: false,
      currentPage: 1, //当前页
      pageSize: 8, //每页显示数
      rows: 0, //总行数
      searchKeyword: "", //搜索框
      searchDate: "", //日期框
      dateString: "",
      saleOutData: [], // 销售订单数据

      tableData: [],
      tableData1: [],
      selectedRows: [], // 存储当前选中的行
      testArr: {
        //虚拟数据
      },
      index: 0,
      isgb: false,
      selectedModelId: 0,
      sal_sales_Outout_id: "",
      Ycchange: false,
      currentPage2: 1, //当前页
      pageSize2: 3, //每页显示数
      modelfroms: 0,
      where: "",

      IshandleReturn: false, //销售退货模态框

      selectedModelId2: 0,
      sal_sales_ReturnReturn_Id: "",
    };
  },
  methods: {
    // //查询仓库名称
    // fetchCK() {
    //   $http
    //     .get("InventoryAlerts/IQuery")
    //     .then((res) => {
    //       this.CK = res;
    //     })
    //     .catch((err) => {
    //       alert(err);
    //     });
    // },

    //库存触发
    setDefaultInventory(row, warehouseName) {
      // 检查 warehouseDefaults 对象中是否存在该仓库的默认值
      const defaultInventory = this.warehouseDefaults[warehouseName];
      if (defaultInventory !== undefined) {
        // 设置默认的库存数量
        row.inventory_quantity = defaultInventory;
      }
    },
    setDefaultInventory2(row, warehouseName) {
      // 检查 warehouseDefaults 对象中是否存在该仓库的默认值
      const defaultInventory = this.warehouseDefaults[warehouseName];
      if (defaultInventory !== undefined) {
        // 设置默认的库存数量
        row.inventory_quantity = defaultInventory;
      }
    },
    //判断出库数量不能大于库存数量
    validateOutboundQuantity(row) {
      if (row.outbound_quantity > row.inventory_quantity) {
        this.$message.error("出库数量不能大于库存数量！");
        // 重置出库数量为库存数量或者之前的合法值
        row.outbound_quantity = Math.min(
          row.outbound_quantity,
          row.inventory_quantity
        );
      }
      if (row.outbound_quantity > row.order_quantity) {
        this.$message.error("出库数量不能大于订单数量！");
        // 如果出库数量大于订单数量，则重置出库数量为订单数量
        row.outbound_quantity = row.order_quantity;
      }
    },
    validateOutboundQuantity2(row) {
      if (row.outbound_quantity > row.inventory_quantity) {
        this.$message.error("出库数量不能大于库存数量！");
        // 重置出库数量为库存数量或者之前的合法值
        row.outbound_quantity = Math.min(
          row.outbound_quantity,
          row.inventory_quantity
        );
      }
      if (row.outbound_quantity > row.order_quantity) {
        this.$message.error("出库数量不能大于订单数量！");
        // 如果出库数量大于订单数量，则重置出库数量为订单数量
        row.outbound_quantity = row.order_quantity;
      }
    },
    //选中行
    handleSelectionChange(selection) {
      this.selectedRows = selection; // 更新选中的行
    },
    //销售出库主表添加
    async MainAdd() {
      let isFormEmpty = true;
      if (
        !this.formCus.client_head &&
        !this.formCus.so_packaging &&
        !this.formCus.so_c_property &&
        !this.formCus.employee_name &&
        !this.formCus.so_sales_date
      ) {
        this.$message.error("数据不能为空，请填写完整表单");
        isFormEmpty = false;
      } else {
        let errorMessage = "";
        if (!this.formCus.client_head) {
          errorMessage = "客户联系人不能为空";
        }
        if (!this.formCus.so_packaging) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "打包方式不能为空";
        }
        if (!this.formCus.so_c_property) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "客户属性不能为空";
        }
        if (!this.formCus.employee_name) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "操作人员不能为空";
        }
        if (!this.formCus.out_sales_date) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "出库日期不能为空";
        }

        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }
      }

      if (!isFormEmpty) {
        return;
      }

      const kh = this.formCus.so_c_property.toString();
      this.mainData = {
        out_code: this.formCus.out_code,
        client_head: this.formCus.client_head,
        client_name: this.formCus.client_name,
        client_phone: this.formCus.client_phone,
        so_packaging: this.formCus.so_packaging,
        so_c_property: kh,
        so_shipment_status: "0",
        employee_name: this.formCus.employee_name,
        out_sales_date: this.formCus.out_sales_date,
        so_status: "1",
        so_created_by: this.username,
        so_created_time: new Date().toISOString(),
        so_update_by: this.username,
        so_update_time: new Date().toISOString(),
        isDeleted: false,
        OutAuditStatus: false,
        sal_sales_out_c: this.tableData1,

        auditor: null, //审核人
        auditTime: null, //审核时间
        out_Return_status: "0", //退货状态
      };
      $http
        .post("SalesOut/AddOutMain", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("添加成功！");
            this.fetchData();
            this.isAddModalVisible = false;
            // 清空文本框字段
            this.formCus.client_head;
            this.formCus.client_name = "";
            this.formCus.client_phone = "";
            this.formCus.so_packaging;
            this.formCus.so_c_property = "";
            this.formCus.so_shipment_status = "";
            this.formCus.employee_name;
            this.formCus.out_sales_date = "";
            this.computedAmountDue = "";
          } else {
            this.$message.error("添加失败！请重新添加！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },

    //日期转型
    formatDate(dateString) {
      if (!dateString) {
        return "";
      }
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        return "";
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    //分页查询仓库
    async fetchData() {
      this.dateString = moment(this.searchDate).format("YYYY-MM-DD");
      this.where = "1=1";
      if (this.searchDate) {
        this.where += `and (CAST(out_sales_date AS DATE) ='${this.dateString}')`;
      }
      if (this.searchKeyword) {
        this.where += `and (client_head like '%${this.searchKeyword}%' or client_name like '%${this.searchKeyword}%' or employee_name like '%${this.searchKeyword}%' or out_code like '%${this.searchKeyword}%')`;
      }
      $http
        .get("SalesOut/getFenYe", {
          params: {
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            where: this.where,
          },
        })
        .then((res) => {
          // this.saleOutData = res.saleOutData.map((sale) => {
          //   return {
          //     ...sale,
          //     so_shipment_status:
          //       sale.so_shipment_status === "1" ? "已发货" : "未发货",
          //   };
          // });
          // this.rows = res.rows;
          this.saleOutData = res.saleOutData;
          this.rows = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    change: function (size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchData();
    },
    Ymchange: function (page) {
      this.currentPage = page;
      this.fetchData();
    },
    //删除
    handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个进行删除");
        return;
      }
      const auditedRows = this.selectedRows.filter(
        (row) => row.outAuditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售出库订单中已有部分订单已经审核通过，不能删除数据"
        );
        return;
      }

      this.$confirm("此操作将删除选中的销售出库订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.deleteSaleOrder(row.out_id);
          });
          this.fetchData();
          this.selectedRows = [];
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteSaleOrder(out_id) {
      $http
        .delete(`SalesOut/FromDelete/${out_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("删除失败，请稍后再试");
          console.error("Delete error:", error);
        });
    },
    //返回列表
    returnToList() {
      this.isAddModalVisible = false;
      this.formCus.client_head = "";
      this.formCus.client_name = "";
      this.formCus.client_phone = "";
      this.formCus.so_packaging = "";
      this.formCus.so_c_property = "";
      this.formCus.so_shipment_status = "";
      this.formCus.employee_name = "";
      this.formCus.so_preferential = "";
      this.formCus.so_freight = "";
      this.formCus.so_amount_due = "";
      this.formCus.so_to_pay = "";
      this.formCus.so_sales_date = "";
      this.tableData1 = [];
      this.tableData1.splice(0, this.tableData1.length);
      this.currentSequence = 1;
    },
    //销售订单模态框
    showAddModal() {
      this.isAddModalVisible = true;
    },
    // 生成新的销售订单编号
    generateOrderNumber() {
      // 获取当前的年月日
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, "0");
      const day = currentDate.getDate().toString().padStart(2, "0");

      // 构建新的订单编号
      const newOrderNumber = `XSCK${year}${month}${day}${this.currentSequence
        .toString()
        .padStart(2, "0")}`;

      // 序列号递增
      this.currentSequence += 1;

      return newOrderNumber;
    },
    //添加产品模态框
    proaddmodel() {
      this.isAddProductVisible = false;
      const newOrderNumber = this.generateOrderNumber();
      const selectedProductName = this.selectedProduct; // 用户选择的产品名称
      const selectedWarehouse = this.selectedWarehouse; // 用户选择的仓库
      console.log(this.selectedProductName);

      this.tableData1.push({
        out_c_code: newOrderNumber,
        orders_product_name: selectedProductName,
        w_Name: selectedWarehouse,
        inventory_quantity: "",
        order_quantity: "",
        outbound_quantity: "",
      });
    },
    //修改产品模态框
    proUpdatemodel() {
      this.isAddProductVisible = false;
      const newOrderNumber = this.generateOrderNumber();
      const selectedProductName = this.selectedProduct; // 用户选择的产品名称
      const selectedWarehouse = this.selectedWarehouse; // 用户选择的仓库
      if (!this.tableData) {
        this.tableData = [];
      }
      this.tableData.push({
        out_c_code: newOrderNumber,
        orders_product_name: selectedProductName,
        w_Name: selectedWarehouse,
        inventory_quantity: "",
        order_quantity: "",
        outbound_quantity: "",
      });
    },
    // 当客户联系人选择变化时触发
    onCustomerContactChange(selectedContact) {
      const contactInfo = this.contacts.find(
        (c) => c.client_head === selectedContact
      );
      if (contactInfo) {
        this.formCus.client_name = contactInfo.client_name;
        this.formCus.client_phone = contactInfo.client_phone;
      }
    },
    // 加载客户联系人数据
    loadContacts() {
      $http
        .get("bs_client/Index")
        .then((response) => {
          if (response) {
            this.contacts = response;
          } else {
            console.error("Invalid response format:", response);
          }
        })
        .catch((error) => {
          console.error("Error fetching contacts:", error);
        });
    },
    // 加载操作人员数据
    loadEmployee() {
      $http
        .get("Employee/Query")
        .then((response) => {
          if (response) {
            this.employees = response;
          } else {
            console.error("Invalid response format:", response);
          }
        })
        .catch((error) => {
          console.error("Error fetching contacts:", error);
        });
    },
    //客户属性下拉
    fetchCUs() {
      $http
        .get("dict_data/Queryclient")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.list = response;
          this.list.forEach((item) => {
            console.log(item.dd_label);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //产品名称下拉
    fetchProducts() {
      $http
        .get("InvGoodsInventory/Query")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.products = response;
          this.products.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    // 根据产品查询仓库
    fetchWarehousesByProduct(productName) {
      // 向后端发送请求，查询对应产品的出库仓库信息
      $http
        .get("InvGoodsInventory/QueryWarehouseByName", {
          params: { igi_name: productName },
        })
        .then((response) => {
          // 处理返回的出库仓库信息
          this.CK = response;
        })
        .catch((error) => {
          console.error("Error fetching warehouses by product name:", error);
        });
    },

    // 根据产品名称和仓库名称查询库存数量
    fetchInventoryByWarehouse(row, productName, warehouseName) {
      $http
        .get("InvGoodsInventory/QueryInventoryQuantityByProductAndWarehouse", {
          params: { igi_name: productName, igi_warehouse: warehouseName },
        })
        .then((response) => {
          const inventory_quantity = response.igi_quantity;
          row.inventory_quantity = inventory_quantity; // 将库存数量赋值给表格数据中的 inventory_quantity 字段
        })
        .catch((error) => {
          console.error(
            "Error fetching inventory by product and warehouse:",
            error
          );
        });
    },
    // 根据产品名称和仓库名称查询库存数量
    fetchInventoryByWarehouse2(row, productName, warehouseName) {
      $http
        .get("InvGoodsInventory/QueryInventoryQuantityByProductAndWarehouse", {
          params: { igi_name: productName, igi_warehouse: warehouseName },
        })
        .then((response) => {
          const inventory_quantity = response.igi_quantity;
          row.inventory_quantity = inventory_quantity; // 将库存数量赋值给表格数据中的 inventory_quantity 字段
        })
        .catch((error) => {
          console.error(
            "Error fetching inventory by product and warehouse:",
            error
          );
        });
    },

    //产品名称下拉
    fetchProducts2() {
      $http
        .get("dict_image/Queryproducts")
        .then((response) => {
          // 根据type属性过滤出单位数据
          this.productss = response;
          this.productss.forEach((product) => {
            console.log(product.di_name);
          });
        })
        .catch((error) => {
          console.error("Error fetching units from dictionary:", error);
        });
    },
    //销售出库审核
    handleOutAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一个销售订单进行审核");
        return;
      }
      const auditedRows = this.selectedRows.filter(
        (row) => row.outAuditStatus === true
      );
      if (auditedRows.length > 0) {
        this.$message.warning(
          "选中的销售订单中已有部分订单已经审核通过，不能再次审核"
        );
        return;
      }

      this.$confirm("此操作将审核选中的销售订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.selectedRows.forEach((row) => {
            this.auditSaleOrder(row.out_id);
          });
          this.selectedRows = [];
          this.fetchData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消审核",
          });
        });
    },
    //审核方法
    auditSaleOrder(out_id) {
      $http
        .post(`SalesOut/AuditSalesOrder/${out_id}`)
        .then((response) => {
          this.$message({
            message: response,
            type: "success",
          });
          this.fetchData();
        })
        .catch((error) => {
          this.$message.error("审核失败，请稍后再试");
          console.error("Audit error:", error);
        });
    },
    //查看模态框
    handleSee(row) {
      const statusMap = {
        未完成: "0",
        待出库: "1",
        已出库: "2",
      };
      const so_shipment_statusMap = {
        未发货: "0",
        已发货: "1",
      };
      const mappedStatus = statusMap[row.so_status] || "1 ";
      const mappedStatus2 =
        so_shipment_statusMap[row.so_shipment_status] || "0";
      this.isUpdateModalVisible = true;
      this.selectedModelId = row.out_id;
      this.formCusUpdate.sal_sales_Outout_id = this.selectedModelId;
      this.fetchData();
      this.fetchUpaheModeFrom();
      this.$set(this.formCusUpdate, "out_id", row.out_id);
      this.$set(this.formCusUpdate, "out_code", row.out_code);
      this.$set(this.formCusUpdate, "so_shipment_status", mappedStatus2);
      this.$set(this.formCusUpdate, "so_status", mappedStatus);
      this.$set(this.formCusUpdate, "client_head", row.client_head);
      this.$set(this.formCusUpdate, "client_name", row.client_name);
      this.$set(this.formCusUpdate, "client_phone", row.client_phone);
      this.$set(this.formCusUpdate, "so_packaging", row.so_packaging);
      this.$set(this.formCusUpdate, "so_c_property", row.so_c_property);
      this.$set(this.formCusUpdate, "employee_name", row.employee_name);
      this.$set(this.formCusUpdate, "out_sales_date", row.out_sales_date);
      this.$set(this.formCusUpdate, "outAuditStatus", row.outAuditStatus);

      this.$set(this.formCusUpdate, "auditor", row.auditor);
      this.$set(this.formCusUpdate, "auditTime", row.auditTime);
      this.$set(this.formCusUpdate, "out_Return_status", row.out_Return_status);
      this.$set(
        this.formCusUpdate,
        " out_Return_status",
        row.out_Return_status
      );
    },
    //修改分页
    fetchUpaheModeFrom() {
      this.where = "sal_sales_Outout_id=" + this.selectedModelId;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("SalesOut/getFenYeC", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.tableData = res.tableData;
          this.modelfroms = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    fetchUpaheModeFrom2() {
      this.where = "sal_sales_Outout_id=" + this.selectedModelId2;
      // 向后端请求数据，并更新客户数据和总条数
      $http
        .get("SalesOut/getFenYeC", {
          params: {
            currentPage: this.currentPage2,
            pageSize: this.pageSize2,
            where: this.where,
          },
        })
        .then((res) => {
          this.tableData = res.tableData;
          this.modelfroms = res.rows;
        })
        .catch((error) => {
          console.error("Error fetching client data: ", error);
        });
    },
    changeModel: function (size) {
      this.pageSize2 = size;
      this.currentPage2 = 1;
      this.fetchUpaheModeFrom(); // 切换每页显示数后重新获取数据
      this.fetchUpaheModeFrom2();
    },
    YmchangeModel: function (page) {
      this.currentPage2 = page;
      this.fetchUpaheModeFrom(); // 重新获取数据
      this.fetchUpaheModeFrom2();
    },
    //查看修改
    MainUpdate() {
      const updateData = {
        // 主表数据
        out_id: this.formCusUpdate.out_id,
        out_code: this.formCusUpdate.out_code,
        client_head: this.formCusUpdate.client_head,
        so_c_property: this.formCusUpdate.so_c_property,
        so_packaging: this.formCusUpdate.so_packaging,
        client_name: this.formCusUpdate.client_name,
        client_phone: this.formCusUpdate.client_phone,
        out_sales_date: this.formCusUpdate.out_sales_date,
        so_shipment_status: this.formCusUpdate.so_shipment_status,
        so_status: "1",
        employee_name: this.formCusUpdate.employee_name,
        isDeleted: false,
        so_created_by: this.username,
        so_created_time: new Date(),
        so_update_by: this.username,
        so_update_time: new Date(),
        outAuditStatus: false,
        out_Return_status: this.formCusUpdate.out_Return_status,
        sal_sales_out_c: this.tableData.map((item) => ({
          OutID: item.OutID,
          orders_product_name: item.orders_product_name,
          w_Name: item.w_Name,
          inventory_quantity: item.inventory_quantity,
          order_quantity: item.order_quantity,
          outbound_quantity: item.outbound_quantity,
          isDeleted: item.isDeleted,
          sal_sales_Outout_id: this.formCusUpdate.out_id,
        })),
      };
      // 检查审核状态，如果为 true，则不允许修改
      if (this.formCusUpdate.outAuditStatus === true) {
        this.$message.error("修改失败：该订单已被审核，不能进行修改！");
        return;
      }
      if (
        this.formCusUpdate.out_Return_status == "1" ||
        this.formCusUpdate.out_Return_status == "2"
      ) {
        this.$message.error("修改失败：该订单已提交退货申请，不能进行修改！");
        return;
      }
      $http
        .put("SalesOut/UpdateClient", updateData)
        .then((response) => {
          if (response) {
            this.$message.success("修改成功！");
            this.fetchData();
            this.isUpdateModalVisible = false;
          } else {
            this.$message.error("修改失败！请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },
    //查看删除
    DeleteCustomerXS(outID) {
      console.log(outID);
      MessageBox.confirm("确认删除删除该条记录吗？, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "bs_model",
      })
        .then(() => {
          $http
            .delete(`SalesOut/OutDelete/${outID}`)
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功！",
              });
              this.fetchUpaheModeFrom();
            })
            .catch((error) => {
              this.$message.error("删除失败：" + error.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "管理员取消了删除,删除无效哦！",
          });
        });
    },
    //添加中刪除
    deleteCustomer(index) {
      // 首先确保下标在合法范围内
      if (index >= 0 && index < this.tableData1.length) {
        // 从数组中删除指定下标的元素
        this.tableData1.splice(index, 1);
        // 深拷贝 allData 的值给 testArr
        this.testArr = JSON.parse(JSON.stringify(this.tableData1));
        // 提示用户删除成功
        this.$message.success("删除成功！");
      } else {
        // 如果下标不在合法范围内，给出相应的提示
        this.$message.error("无法删除，下标越界！");
      }
    },
    //从表添加修改
    confirmUpdate(row) {
      // 检查row对象中是否包含OutID，以判断是修改还是添加
      if (row.outID) {
        // 修改操作
        this.updateSubTableData(row);
      } else {
        // 添加操作
        row.sal_sales_Outout_id = this.formCusUpdate.out_id;
        this.addSubTableData(row);
      }
    },
    updateSubTableData(data) {
      $http
        .put("SalesOut/Update_C", data)
        .then((response) => {
          if (response) {
            //this.$message.success("修改成功！");
          } else {
            this.$message.error("修改失败，请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
    },

    addSubTableData(data) {
      $http
        .post("SalesOut/Add_C", data)
        .then((response) => {
          if (response) {
            //this.$message.success("添加成功！");
          } else {
            this.$message.error("添加失败，请重试！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },
    //退货
    handleReturn(row) {
      this.IshandleReturn = true;
      this.selectedModelId2 = row.out_id;
      this.formCusUpdate.sal_sales_Outout_id = this.selectedModelId2;
      this.fetchData();
      this.fetchUpaheModeFrom2();
      this.$set(this.addReturn, "return_Id", row.return_Id);
      this.$set(this.addReturn, "so_code", row.out_code);
      this.$set(this.addReturn, "client_head", row.client_head);
      this.$set(this.addReturn, "client_phone", row.client_phone);
      this.$set(this.addReturn, "employee_name", row.employee_name);
      this.$set(this.addReturn, "auditor", row.auditor);
      this.$set(this.addReturn, "auditTime", row.auditTime);
      this.$set(this.addReturn, "auditStatus", row.outAuditStatus);
      this.$set(this.addReturn, "so_out_status", row.so_status);
      this.$set(this.addReturn, "return_status", row.out_Return_status);
    },
    TuiH() {
      let isFormEmpty = true;
      if (!this.addReturn.returmReason && !this.addReturn.return_date) {
        this.$message.error("数据不能为空，请填写完整表单");
        isFormEmpty = false;
      } else {
        let errorMessage = "";
        if (!this.addReturn.returmReason) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "退货原因不能为空";
        }
        if (!this.addReturn.return_date) {
          if (errorMessage) errorMessage += "; ";
          errorMessage += "退货日期不能为空";
        }

        if (errorMessage) {
          this.$message.error(errorMessage);
          return;
        }
      }
      if (!isFormEmpty) {
        return;
      }

      this.mainData = {
        return_code: this.addReturn.return_code,
        so_code: this.addReturn.so_code,
        client_head: this.addReturn.client_head,
        client_phone: this.addReturn.client_phone,
        return_date: this.addReturn.return_date,
        isDeleted: false,
        auditor: this.addReturn.auditor,
        auditTime: this.addReturn.auditTime,
        outAuditStatus: this.addReturn.outAuditStatus,
        employee_name: this.addReturn.employee_name,
        returmReason: this.addReturn.returmReason,

        return_status: "1",
        so_out_status: this.addReturn.so_out_status,

        sal_sales_Return_C: this.tableData,
      };
      $http
        .post("SalesReturn/AddReturn", this.mainData)
        .then((response) => {
          if (response) {
            this.$message.success("退货成功！");
            this.$router.push("/sale_SaleReturn");
            this.fetchData();
            this.IshandleReturn = false;
          } else {
            this.$message.error("添加失败！请重新添加！");
          }
        })
        .catch((error) => {
          this.$message.error("添加失败：" + error.message);
        });
    },
    // 验证退货数量是否大于销售数量
    validateReturnQuantity(row) {
      if (row.return_quantity > row.outbound_quantity) {
        this.$message.error("退货数量不能大于销售数量");
        // 如果退货数量大于销售数量，则重置为销售数量
        row.return_quantity = row.outbound_quantity;
      }
    },
  },
  mounted() {
    this.fetchUpaheModeFrom();
    this.fetchUpaheModeFrom2();
    this.loadContacts();
    this.fetchCUs();
    this.loadEmployee();
    this.fetchData();
    // this.fetchCK();
    this.fetchProducts();
    this.fetchProducts2();
  },
  computed: {
    displayText2() {
      return this.addReturn.outAuditStatus ? "已审核" : "未审核";
    },
    uniqueList() {
      // 利用Set数据结构对数组进行去重
      const uniqueValues = [
        ...new Set(this.products.map((item) => item.igi_name)),
      ];
      // 根据去重后的值构造对象数组
      const uniqueList = uniqueValues.map((value) => ({
        igi_name: value,
      }));
      return uniqueList;
    },
  },
};
</script>
<style scoped src="../CSS/SaleOrder.css"></style>
<style scoped>
.form-items-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20px;
  /* 两边留出20px的空隙 */
}

/* 设置文本框的样式 */
.el-form-item__content {
  flex-grow: 1;
}

.form-item {
  flex: 0 0 calc(25% - 40px);
  /* 减去两侧各20px的空隙 */
  max-width: 250px;
  /* 设置文本框的最大宽度 */
  margin: 10px 0;
  /* 上下留出10px的空隙 */
}

.el-form-item__label {
  width: 120px;
  /* 可以调整标签的宽度 */
  text-align: right;
  padding-right: 10px;
}

.el-input__inner,
.el-select .el-input {
  max-width: 200px;
  /* 可以调整输入框的最大宽度 */
}

@media (max-width: 800px) {
  .form-item {
    flex-basis: 100%;
    margin: 10px 0;
  }
}

.button-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* 垂直居中 */
  height: 100%;
  /* 确保按钮容器占据整个高度 */
  padding-top: 10px;
  float: left;
}

.custom-button {
  display: flex;
  align-items: center;
  /* 垂直居中 */
  justify-content: center;
  /* 水平居中 */
  background-color: #1abc9c;
  width: 60px;
  height: 30px;
  color: #fff;
  font-size: 12px;
  border: none;
}

.custom-form {
  margin: 20px;
}

.kuang {
  width: 60px;
  font-size: small;
}

.orange-button {
  font-size: small;
}

.addmodel {
  left: 120px;
}

.caoz {
  width: 70px;
  font-size: small;
}
</style>
